package edu.gzhu.guli.back.service.permission;

import java.util.List;
import java.util.Optional;

import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import edu.gzhu.guli.core.common.ApplicationResult;
import edu.gzhu.guli.core.entity.Permission;
import edu.gzhu.guli.core.entity.Permission_;
import edu.gzhu.guli.core.repository.PermissionRepository;
import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class PermissionService {
  private final PermissionRepository permissionRepository;
  private final ModelMapper modelMapper;
  private final PermissionCascadeConverter cascadeConverter;
  public static final Sort ORDER = Sort.by(Permission_.LEVEL);

  public ApplicationResult<List<PermissionCascadeDto>> cascade() {
    List<Permission> permissions = permissionRepository.findAll(ORDER);
    List<PermissionCascadeDto> data = cascadeConverter.convert(permissions);
    return ApplicationResult.succese(data);
  }

  public ApplicationResult<Object> create(PermissionCreateOrEditDto dto) {
    Optional<Permission> check = permissionRepository.findOne(builder -> builder
      .andEquals(Permission_.CODE, dto.getCode()).build());
    if (check.isPresent()) 
      return ApplicationResult.failure("权限编号重复");
    Permission permission = modelMapper.map(dto, Permission.class);
    permission = permissionRepository.save(permission);

    return ApplicationResult.succese();
  }

  public ApplicationResult<Object> edit(Long permissionId, PermissionCreateOrEditDto dto) {
    Optional<Permission> check = permissionRepository.findOne(builder -> builder
    .andEquals(Permission_.CODE, dto.getCode())
    .andNotEquals(Permission_.ID, permissionId)
    .build());
    if (check.isPresent())
      return ApplicationResult.failure("权限编号重复");
    check = permissionRepository.findById(permissionId);
    if (!check.isPresent()) 
      return ApplicationResult.failure("未找到相应权限");
    Permission permission = check.get();
    modelMapper.map(dto, permission);
    permission = permissionRepository.save(permission);
    return ApplicationResult.succese();
  }

  public ApplicationResult<Object> delete(Long permissionId) {
    Optional<Permission> check = permissionRepository.findById(permissionId);
    if (!check.isPresent()) 
      return ApplicationResult.failure("未找到相应权限");
      Permission permission = check.get();
    permissionRepository.delete(permission);
    return ApplicationResult.succese();
  }
}
